package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.EventWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.fragment.CreditFragment;
import com.cardbaobao.cardbabyclient.ui.fragment.DiscoverFragment;
import com.cardbaobao.cardbabyclient.ui.fragment.LoanFragment;
import com.cardbaobao.cardbabyclient.ui.fragment.WalletFragment;
import com.cardbaobao.cardbabyclient.ui.fragment.MineFragment;
import com.cardbaobao.cardbabyclient.ui.fragment.base.BaseFragment;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.gyf.barlibrary.ImmersionBar;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 首页MainActivity
 * Created by zad
 * 2016/8/1 9:22
 */
public class MainActivity extends AppCompatActivity {
    private static final int FRAGMENT_COUNT = 5;
    private String mPrePageId;
    /**
     * 首页
     */
    @BindView(R.id.id_tv_wallet)
    TextView mTvIndex;
    /**
     * 信用卡
     */
    @BindView(R.id.id_tv_credit)
    TextView mTvCredit;
    /**
     * 贷款
     */
    @BindView(R.id.id_tv_loan)
    TextView mTvLoan;
    /**
     * 服务
     */
    @BindView(R.id.id_tv_service)
    TextView mTvService;
    /**
     * 我的
     */
    @BindView(R.id.id_tv_mine)
    TextView mTvMine;

    private Context mContext;

    /**
     * 底部导航栏图标集
     */
    private List<TextView> textViews = new ArrayList<>(FRAGMENT_COUNT);

    /**
     * BaseFragment数组
     */
    public final BaseFragment[] fragments = new BaseFragment[FRAGMENT_COUNT];

    /**
     * 底部导航栏未选中状态图标集
     */
    private int[] mUnSelectedImgIds = {
            R.mipmap.icon_wallet_normal,
            R.mipmap.icon_credit_normal,
            R.mipmap.icon_loan_normal,
            R.mipmap.icon_found_normal,
            R.mipmap.icon_mine_normal};

    /**
     * 底部导航栏选中状态图标集
     */
    private int[] mSelectedImgIds = {
            R.mipmap.icon_wallet_selected,
            R.mipmap.icon_credit_selected,
            R.mipmap.icon_loan_selected,
            R.mipmap.icon_found_selected,
            R.mipmap.icon_mine_selected};

    /**
     * 需要展示的fragment下标位置
     */
    private int showFragIndex = INDEX_WALLET;
    /**
     * 钱包下标
     */
    private static final int INDEX_WALLET = 0;
    /**
     * 信用卡下标
     */
    private static final int INDEX_CREDIT = 1;
    /**
     * 贷款下标
     */
    private static final int INDEX_LOAN = 2;
    /**
     * 发现下标
     */
    private static final int INDEX_DISCOVER = 3;
    /**
     * 我的下标
     */
    private static final int INDEX_MINE = 4;
    /**
     * 被选中字体颜色
     */
    private static final int COLOR_BOTTOM_SELECTED = 0xFFFF9E27;
    /**
     * 未被选中字体颜色
     */
    private static final int COLOR_BOTTOM_UNSELECTED = 0xFF666666;

    private String adUrl;//广告链接，h5页面唤起app，从h5页面传过来的活动链接

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mContext = this;
        initView();

        Intent intent = getIntent();
        mPrePageId = intent.getStringExtra(BaseActivity.PRE_PAGE_ID_S);
        getAdInfo(intent);

        showFragment(showFragIndex);
    }

    private void getAdInfo(Intent intent) {
        if (null != intent) {
            adUrl = intent.getStringExtra(LaunchActivity.URL_FROM_WEB_S);
        }
    }

    /**
     * 去往活动页面
     */
    private void toAdActivity() {
        Intent webIntent = new Intent(this, EventWebViewActivity.class);
        webIntent.putExtra(EventWebViewActivity.WEB_URL_S, adUrl);
        webIntent.putExtra(EventWebViewActivity.WEB_TYPE_I, 39);
        webIntent.putExtra(EventWebViewActivity.WEB_TITLE_S, "活动详情");
        startActivity(webIntent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (!TextUtils.isEmpty(adUrl)) {
            toAdActivity();
        }
    }

    private void initView() {
        textViews.clear();
        textViews.add(mTvIndex);
        textViews.add(mTvCredit);
        textViews.add(mTvLoan);
        textViews.add(mTvService);
        textViews.add(mTvMine);
    }

    @OnClick({R.id.id_tv_wallet, R.id.id_tv_credit, R.id.id_tv_loan, R.id.id_tv_service, R.id.id_tv_mine})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_tv_wallet://钱包
                showFragment(INDEX_WALLET);
                break;
            case R.id.id_tv_credit://信用卡
                showFragment(INDEX_CREDIT);
                break;
            case R.id.id_tv_loan://贷款
                showFragment(INDEX_LOAN);
                break;
            case R.id.id_tv_service://服务
                showFragment(INDEX_DISCOVER);
                break;
            case R.id.id_tv_mine://我的
                showFragment(INDEX_MINE);
                break;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("showFragIndex", showFragIndex);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        showFragIndex = savedInstanceState.getInt("showFragIndex");
        showFragment(showFragIndex);
    }

    /**
     * 显示fragment
     *
     * @param fragmentIndex 当前选中的fragment
     */
    private void showFragment(int fragmentIndex) {
        if (fragmentIndex >= 0 && fragmentIndex < FRAGMENT_COUNT) {
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            switch (fragmentIndex) {
                case INDEX_WALLET:
                    if (manager.findFragmentByTag(String.valueOf(INDEX_WALLET)) == null) {
                        if (fragments[INDEX_WALLET] == null) {
                            WalletFragment walletFragment = new WalletFragment();
                            walletFragment.setBuriedInfo(mPrePageId);
                            fragments[INDEX_WALLET] = walletFragment;
                        }
                    } else {
                        if (fragments[INDEX_WALLET] == null) {
                            WalletFragment walletFragment =
                                    (WalletFragment) manager.findFragmentByTag(String.valueOf(INDEX_WALLET));
                            walletFragment.setBuriedInfo(mPrePageId);
                            fragments[INDEX_WALLET] = walletFragment;
                        }
                    }
                    if (!fragments[INDEX_WALLET].isAdded()) {
                        transaction.add(R.id.id_fragment_container,
                                fragments[INDEX_WALLET],
                                String.valueOf(INDEX_WALLET));
                    }
                    showFragIndex = INDEX_WALLET;
                    break;
                case INDEX_CREDIT:
                    if (manager.findFragmentByTag(String.valueOf(INDEX_CREDIT)) == null) {
                        if (fragments[INDEX_CREDIT] == null) {
                            CreditFragment creditFragment = new CreditFragment();
                            creditFragment.setBuriedInfo(mPrePageId);
                            fragments[INDEX_CREDIT] = creditFragment;
                        }
                    } else {
                        if (fragments[INDEX_CREDIT] == null) {
                            CreditFragment creditFragment =
                                    (CreditFragment) manager.findFragmentByTag(String.valueOf(INDEX_CREDIT));
                            creditFragment.setBuriedInfo(mPrePageId);
                            fragments[INDEX_CREDIT] = creditFragment;
                        }
                    }
                    if (!fragments[INDEX_CREDIT].isAdded()) {
                        transaction.add(R.id.id_fragment_container,
                                fragments[INDEX_CREDIT],
                                String.valueOf(INDEX_CREDIT));
                    }
                    showFragIndex = INDEX_CREDIT;
                    break;
                case INDEX_LOAN:
                    if (manager.findFragmentByTag(String.valueOf(INDEX_LOAN)) == null) {
                        if (fragments[INDEX_LOAN] == null) {
                            LoanFragment loanFragment = new LoanFragment();
                            loanFragment.setBuriedInfo(mPrePageId);
                            fragments[INDEX_LOAN] = loanFragment;
                        }
                    } else {
                        if (fragments[INDEX_LOAN] == null) {
                            LoanFragment loanFragment =
                                    (LoanFragment) manager.findFragmentByTag(String.valueOf(INDEX_LOAN));
                            loanFragment.setBuriedInfo(mPrePageId);
                            fragments[INDEX_LOAN] = loanFragment;
                        }
                    }
                    if (!fragments[INDEX_LOAN].isAdded()) {
                        transaction.add(R.id.id_fragment_container,
                                fragments[INDEX_LOAN],
                                String.valueOf(INDEX_LOAN));
                    }
                    showFragIndex = INDEX_LOAN;
                    break;
                case INDEX_DISCOVER:
                    if (manager.findFragmentByTag(String.valueOf(INDEX_DISCOVER)) == null) {
                        if (fragments[INDEX_DISCOVER] == null) {
                            DiscoverFragment discoverFragment = new DiscoverFragment();
                            discoverFragment.setBuriedInfo(mPrePageId);
                            fragments[INDEX_DISCOVER] = discoverFragment;
                        }
                    } else {
                        if (fragments[INDEX_DISCOVER] == null) {
                            DiscoverFragment discoverFragment =
                                    (DiscoverFragment) manager.findFragmentByTag(String.valueOf(INDEX_DISCOVER));
                            discoverFragment.setBuriedInfo(mPrePageId);
                            fragments[INDEX_DISCOVER] = discoverFragment;
                        }
                    }
                    if (!fragments[INDEX_DISCOVER].isAdded()) {
                        transaction.add(R.id.id_fragment_container,
                                fragments[INDEX_DISCOVER],
                                String.valueOf(INDEX_DISCOVER));
                    }
                    showFragIndex = INDEX_DISCOVER;
                    break;
                case INDEX_MINE:
                    if (manager.findFragmentByTag(String.valueOf(INDEX_MINE)) == null) {
                        if (fragments[INDEX_MINE] == null) {
                            MineFragment mineFragment = new MineFragment();
                            mineFragment.setBuriedInfo(mPrePageId);
                            fragments[INDEX_MINE] = mineFragment;
                        }
                    } else {
                        if (fragments[INDEX_MINE] == null) {
                            MineFragment mineFragment =
                                    (MineFragment) manager.findFragmentByTag(String.valueOf(INDEX_MINE));
                            mineFragment.setBuriedInfo(mPrePageId);
                            fragments[INDEX_MINE] = mineFragment;
                        }
                    }
                    if (!fragments[INDEX_MINE].isAdded()) {
                        transaction.add(R.id.id_fragment_container,
                                fragments[INDEX_MINE],
                                String.valueOf(INDEX_MINE));
                    }
                    showFragIndex = INDEX_MINE;
                    break;
                default:
                    if (manager.findFragmentByTag(String.valueOf(INDEX_WALLET)) == null) {
                        if (fragments[INDEX_WALLET] == null) {
                            WalletFragment walletFragment = new WalletFragment();
                            walletFragment.setBuriedInfo(mPrePageId);
                            fragments[INDEX_WALLET] = walletFragment;
                        }
                    } else {
                        if (fragments[INDEX_WALLET] == null) {
                            WalletFragment walletFragment =
                                    (WalletFragment) manager.findFragmentByTag(String.valueOf(INDEX_WALLET));
                            fragments[INDEX_WALLET] = walletFragment;
                        }
                    }
                    if (!fragments[INDEX_WALLET].isAdded()) {
                        transaction.add(R.id.id_fragment_container,
                                fragments[INDEX_WALLET],
                                String.valueOf(INDEX_WALLET));
                    }
                    showFragIndex = INDEX_WALLET;
                    break;
            }
            if (showFragIndex == INDEX_CREDIT ||
                    showFragIndex == INDEX_LOAN ||
                    showFragIndex == INDEX_DISCOVER) {
                ImmersionBar.with(this).statusBarDarkFont(true, Constant.STATUS_BAR_FONT_ALPHA).init();
            } else {
                ImmersionBar.with(this).statusBarDarkFont(false).init();
            }
            TextView tv;
            Fragment fragment;
            for (int i = 0; i < fragments.length; i++) {
                fragment = fragments[i];
                if (i == showFragIndex) {
                    tv = textViews.get(i);
                    tv.setTextColor(COLOR_BOTTOM_SELECTED);
                    tv.setCompoundDrawablesWithIntrinsicBounds(null,
                            ContextCompat.getDrawable(getApplicationContext(),
                                    mSelectedImgIds[i]), null, null);
                    if (fragment != null) {
                        transaction.show(fragment);
                    }
                } else {
                    tv = textViews.get(i);
                    tv.setTextColor(COLOR_BOTTOM_UNSELECTED);
                    tv.setCompoundDrawablesWithIntrinsicBounds(null,
                            ContextCompat.getDrawable(getApplicationContext(),
                                    mUnSelectedImgIds[i]), null, null);
                    if (fragment != null) {
                        transaction.hide(fragment);
                    }
                }
            }
            transaction.commit();

        }
        //友盟埋点屏幕事件，需要在onResume后调用
        if (onResumed) {
            countUmengScreen();
        }
    }

    /**
     * 统计友盟页面启动事件
     */
    private void countUmengScreen() {
        switch (showFragIndex) {
            case 0:
                //首页 event_0x002
                UmengEventUtils.pageEvent(mContext, getString(R.string.event_0x044));
                break;
            case 1:
                //信用卡
                UmengEventUtils.pageEvent(mContext, getString(R.string.event_0x045));
                break;
            case 2:
                //贷款
                UmengEventUtils.pageEvent(mContext, getString(R.string.event_0x046));
                break;
            case 3:
                //发现
                UmengEventUtils.pageEvent(mContext, getString(R.string.event_0x047));
                break;
            case 4:
                //我的
                UmengEventUtils.pageEvent(mContext, getString(R.string.event_0x048));
                break;
        }
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.showToast("再按一次退出" +
                        ApplicationHelper.getApplicationContext().getString(R.string.app_name));
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private boolean onResumed;

    @Override
    protected void onResume() {
        super.onResume();
        onResumed = true;
        MobclickAgent.onResume(this);//友盟统计
        countUmengScreen();
    }

    @Override
    protected void onPause() {
        super.onPause();
        onResumed = false;
        MobclickAgent.onPause(this);//友盟统计
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ToastUtil.cancelToast();
        ImmersionBar.with(this).destroy();
        UMShareAPI.get(this).release();
    }

    /**
     * 分享回调
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

}
